﻿using DLL;
using NursingFormSystem.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace NursingFormSystem.Hypoglycemia
{
    public partial class HistoryHypoglycemia : Form
    {
        #region 变量声明
        public NursingFormSystem.NurFormsService.NursingForm formService = new NursingFormSystem.NurFormsService.NursingForm();
        Tb_User LoginUser;
        PatientInfo PatientInfo;
        int SumDiXueTangRenShu = 0;       //计算低血糖人数
        int SumDiXueTangCiShu = 0;        //计算低血糖发生次数
        int SumTangNiaoBingRenShu = 0;    //糖尿病人数
        int SumXueTangCeShiCiShu = 0;      //血糖测试次数
        List<string> PatientNameList = new List<string>();//病区患者列表
        List<int> PatientDiXueTangCiShuList = new List<int>();//低血糖发生次数
        List<int> PatientXueTangCiShuList = new List<int>();//血糖测试次数
        string DiXueTangFaShengShiJian;
        List<string> ZhuYuanCiShuList = new List<string>();
        List<string> HUanZheIDList = new List<string>();
        int[] notBloodsugarIndexArr = { 8, 10, 12, 14, 16, 18 };
        #endregion

        #region 构造函数
        public HistoryHypoglycemia(Tb_User loginUser, PatientInfo patientInfo)
        {
            InitializeComponent();
            LoginUser = loginUser;
            PatientInfo = patientInfo;
            BindControl();   //绑定控件数据
            BindInfo();    //绑定信息数据
        }
        public HistoryHypoglycemia(string[] loginUser, string[] patientInfo)
        {
            InitializeComponent();
            LoginUser = ArrayToObject.ArrayToLoginUser(loginUser);
            PatientInfo = ArrayToObject.ArrayToPatientInfo(patientInfo);
            BindControl();   //绑定控件数据
            BindInfo();    //绑定信息数据
        }
        #endregion

        #region 查询病区--所有
        private void BindControl()
        {
            StatDate.DateTime = DateTime.Now.AddDays(-30).Date;
            EndDate.DateTime = DateTime.Now;
            string sql = "select distinct(AreaName) from dbo.t_Bloodsugar(NOLOCK)";
            DataSet ds = SqlHelper.ExecuteDataset(sql);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                comBingQu.Properties.Items.Add(row["AreaName"]);
            }

            if (comBingQu.Properties.Items.Count > 0)
                comBingQu.SelectedIndex = 0;
        }
        #endregion

        #region 查询
        private void btnchaxun_Click(object sender, EventArgs e)
        {
            BindInfo();
        }
        #endregion

        #region 计算低血糖人数
        public void Count(DataRow dr)
        {
            var data = Convert.ToString(dr["data"]);
            XmlDocument xmlDoc = new XmlDocument();
            StringReader Nurseingdata = new StringReader(data.ToString());
            xmlDoc.Load(Nurseingdata);
            XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
            for (int i = 0; i < 20; i++)
            {
                if (notBloodsugarIndexArr.Contains(i)) continue;
                string val = nursingrecord.ChildNodes[i].InnerText;
                if (RegexHelper.IsDouble(val) && Convert.ToDouble(val) < 2.81)
                {
                    SumDiXueTangRenShu++; return;
                }
            }
        }
        #endregion

        #region 计算低血糖发生次数
        public void Counts(DataRow dr)
        {
            var data = Convert.ToString(dr["data"]);
            XmlDocument xmlDoc = new XmlDocument();
            StringReader Nurseingdata = new StringReader(data.ToString());
            xmlDoc.Load(Nurseingdata);
            XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
            for (int i = 0; i < 20; i++)
            {
                if (notBloodsugarIndexArr.Contains(i)) continue;
                string val = nursingrecord.ChildNodes[i].InnerText;
                if (RegexHelper.IsDouble(val) && Convert.ToDouble(val) < 2.81)    //凌晨3时
                {
                    SumDiXueTangCiShu++;
                }
            }
        }
        #endregion

        #region 糖尿病人数
        public void CountTangNiaoBing(DataRow dr)
        {
            var data = Convert.ToString(dr["data"]);
            XmlDocument xmlDoc = new XmlDocument();
            StringReader Nurseingdata = new StringReader(data.ToString());
            xmlDoc.Load(Nurseingdata);
            XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");

            for (int i = 0; i < 20; i++)
            {
                if (notBloodsugarIndexArr.Contains(i)) continue;
                string val = nursingrecord.ChildNodes[i].InnerText;
                if (RegexHelper.IsDouble(val) && Convert.ToDouble(val) < 3.91)
                {
                    SumTangNiaoBingRenShu++; return;
                }
            }

        }
        #endregion

        #region 血糖测试次数
        public void CountXueTangCeShiCiShu(DataRow dr)
        {
            var data = Convert.ToString(dr["data"]);
            XmlDocument xmlDoc = new XmlDocument();
            StringReader Nurseingdata = new StringReader(data.ToString());
            xmlDoc.Load(Nurseingdata);
            XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
            for (int i = 0; i < 20; i++)
            {
                if (notBloodsugarIndexArr.Contains(i)) continue;
                if (RegexHelper.IsDouble(nursingrecord.ChildNodes[i].InnerText))
                {
                    SumXueTangCeShiCiShu++;
                }
            }
        }
        #endregion

        #region 统计显示所有患者
        public void TongJiSuoYouHuanZhe()
        {
            string tempTJYHZ = @"SELECT distinct PatientName,VISIT_ID,PatientId  FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar](NOLOCK) where patientId not LIKE '%删除%' and AreaName ='" + comBingQu.Text + "'";
            DataSet dsTJYHZ = SqlHelper.ExecuteDataset(tempTJYHZ, System.Data.CommandType.Text);
            for (int i = 0; i < dsTJYHZ.Tables[0].Rows.Count; i++)
            {
                PatientNameList.Add(dsTJYHZ.Tables[0].Rows[i]["PatientName"].ToString());
                ZhuYuanCiShuList.Add(dsTJYHZ.Tables[0].Rows[i]["VISIT_ID"].ToString());
                HUanZheIDList.Add(dsTJYHZ.Tables[0].Rows[i]["PatientId"].ToString());
            }

        }
        #endregion

        #region 统计显示单个患者的低血糖次数
        public void DiXueTangCiShu(List<string> PatientNameList)
        {
            int count = 0;
            foreach (var item in PatientNameList)
            {
                count = DangQianDiXueTangCounts(item);
                PatientDiXueTangCiShuList.Add(count);
            }
        }
        #endregion

        #region 统计显示单个患者的血糖测试次数
        public void XueTangCeShiCiShu(List<string> PatientNameList)
        {
            int count = 0;
            foreach (var item in PatientNameList)
            {
                count = XueTangCeShiCiShuCounts(item);
                PatientXueTangCiShuList.Add(count);
            }
        }
        #endregion

        #region 统计显示单个患者的血糖测试次数的方法
        private int XueTangCeShiCiShuCounts(string item)
        {
            int count = 0;
            string F = string.Format("'{0} {1}'", this.EndDate.Text, "23:59:59");
            string sql = "select data from t_Bloodsugar(NOLOCK) where PatientId not LIKE '%删除%' and PatientName =  '" + item + "' and Date  >= '" + this.StatDate.Text + "' and  Submittime <= " + F + "";
            DataSet dst = SqlHelper.ExecuteDataset(sql, CommandType.Text);
            DataRowCollection rows = dst.Tables[0].Rows;
            foreach (DataRow dr in rows)
            {
                string data = Convert.ToString(dr["data"]);
                XmlDocument xmlDoc = new XmlDocument();
                StringReader Nurseingdata = new StringReader(data.ToString());
                xmlDoc.Load(Nurseingdata);
                XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
                for (int i = 0; i < 20; i++)
                {
                    if (notBloodsugarIndexArr.Contains(i)) continue;
                    if (!string.IsNullOrEmpty(nursingrecord.ChildNodes[i].InnerText))
                    {
                        count++;
                    }
                }
            }
            return count;
        }
        #endregion

        #region 统计显示单个患者的低血糖次数的方法
        private int DangQianDiXueTangCounts(string item)
        {
            int count = 0;
            string G = string.Format("'{0} {1}'", this.EndDate.Text, "23:59:59");
            string sql = "select Date, data from t_Bloodsugar(NOLOCK) where PatientId not LIKE '%删除%' and  PatientName = '" + item + "' and Date  >= '" + this.StatDate.Text + "' and  Submittime <= " + G + "";
            DataSet dst = SqlHelper.ExecuteDataset(sql, CommandType.Text);
            DataRowCollection rows = dst.Tables[0].Rows;
            foreach (DataRow dr in rows)
            {
                string data = Convert.ToString(dr["data"]);
                XmlDocument xmlDoc = new XmlDocument();
                StringReader Nurseingdata = new StringReader(data.ToString());
                xmlDoc.Load(Nurseingdata);
                XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
                for (int i = 0; i < 20; i++)
                {
                    if (notBloodsugarIndexArr.Contains(i)) continue;
                    string val = nursingrecord.ChildNodes[i].InnerText;
                    if (RegexHelper.IsDouble(val) && Convert.ToDouble(val) < 2.81)
                    {
                        count++;
                        if (string.IsNullOrEmpty(DiXueTangFaShengShiJian))
                        {
                            DiXueTangFaShengShiJian = Convert.ToString(dr["Date"]);
                        }
                    }
                }
            }
            return count;
        }
        #endregion

        #region 查询所有
        public void BindInfo() { BindInfo("", ""); }
        #endregion

        #region 绑定数据信息
        public void BindInfo(string StatDate, string EndDate)
        {
            #region gridcontrol患者信息
            PatientNameList = new List<string>();
            PatientDiXueTangCiShuList = new List<int>();
            PatientXueTangCiShuList = new List<int>();
            SumDiXueTangRenShu = 0;       //计算低血糖人数
            SumDiXueTangCiShu = 0;        //计算低血糖发生次数
            SumTangNiaoBingRenShu = 0;    //糖尿病人数
            SumXueTangCeShiCiShu = 0;      //血糖测试次数
            #endregion
            //结束时间
            string temp = @"SELECT *  FROM [BNNursingDocsSystem_Develop].[dbo].[t_Bloodsugar](NOLOCK) WHERE AreaName ='{0}' AND Date  >= '{1}' AND  Submittime <= '{2}'";
            temp = string.Format(temp, comBingQu.Text, this.StatDate.Text, this.EndDate.Text + " 23:59:59");
            DataSet ds = SqlHelper.ExecuteDataset(temp);
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                #region 计算低血糖人数
                Count(ds.Tables[0].Rows[i]);
                textDiXueTangRenShu.Text = SumDiXueTangRenShu.ToString();
                #endregion
                #region 计算低血糖发生次数
                Counts(ds.Tables[0].Rows[i]);
                textDiXueTangFaShengCiShu.Text = SumDiXueTangCiShu.ToString();
                #endregion
                #region 糖尿病人数
                CountTangNiaoBing(ds.Tables[0].Rows[i]);
                textTangNiaoBingRenShu.Text = SumTangNiaoBingRenShu.ToString();
                #endregion
                #region 血糖测试次数
                CountXueTangCeShiCiShu(ds.Tables[0].Rows[i]);
                textXueTangCeShiCiShu.Text = SumXueTangCeShiCiShu.ToString();
                #endregion
            }
            #region gridcontrol信息
            TongJiSuoYouHuanZhe();                     //病区患者列表
            DiXueTangCiShu(this.PatientNameList);      //低血糖发生次数
            XueTangCeShiCiShu(this.PatientNameList);   //血糖测试次数
            #endregion
            if (this.PatientInfo == null) return;
            string patientid = this.PatientInfo.PATIENT_ID;   //住院号
            int VisitId = this.PatientInfo.VISIT_ID;   //住院次数
            StringBuilder sql = new StringBuilder(@" SELECT  * , '' AS data, '' AS BingQu , '' AS HuanZheXingMing, '' AS DiXueTangRenShu , '' AS DiXueTangFaShengCiShu , '' AS TangNiaoBingRenShu , '' AS XueTangCeShiCiShu , '' AS FaShengLv_1 , '' AS FaShengLv_2 FROM    dbo.t_Bloodsugar(NOLOCK) ");
            sql.AppendFormat("WHERE patientid = '{0}'", patientid);
            if (!string.IsNullOrEmpty(StatDate))
                sql.AppendFormat(" AND [AssessmentDate] >= '{0}'", StatDate + " 00:00:00");
            if (!string.IsNullOrEmpty(EndDate))
                sql.AppendFormat(" AND [AssessmentDate] < '{0}'", Convert.ToDateTime(EndDate).AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"));
            DataTable dt = (SqlHelper.ExecuteDataset(sql.ToString(), CommandType.Text)).Tables[0];
            DataTable dtt = dt.Clone();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var data = Convert.ToString(dr["data"]);
                    Glycopenia go = new Glycopenia();
                    XmlDocument xmlDoc = new XmlDocument();
                    StringReader Nurseingdata = new StringReader(data.ToString());
                    xmlDoc.Load(Nurseingdata);
                    XmlNode nursingrecord = xmlDoc.SelectSingleNode("/BloodSugarRecordDocument");
                    comBingQu.Text = PatientInfo.NURSE_CELL_NAME;    //病区
                    #region 发生率_1的计算值
                    Double Fy = 0;
                    if (Convert.ToDouble(SumDiXueTangRenShu) > 0 && (Convert.ToDouble(SumDiXueTangRenShu) > 0))
                        Fy = (Convert.ToDouble(SumDiXueTangRenShu) / Convert.ToDouble(SumTangNiaoBingRenShu));
                    if (Fy != 0)
                    {
                        textFaShengLv_1.Text = (Fy * 100).ToString("F2");
                    }
                    #endregion
                    #region 发生率_2的计算值
                    Double Ft = 0;
                    if (Convert.ToDouble(SumDiXueTangRenShu) > 0 && Convert.ToDouble(SumXueTangCeShiCiShu) > 0)
                        Ft = (Convert.ToDouble(SumDiXueTangRenShu) / Convert.ToDouble(SumXueTangCeShiCiShu));
                    if (Ft != 0)
                    {
                        textFaShengLv_2.Text = (Ft * 100).ToString("F2");
                    }
                    #endregion
                }
            }
            DataTable dte = new DataTable();
            dte.Columns.Add("HuanZheXingMing", typeof(string));
            dte.Columns.Add("DiXueTangFaShengCiShu", typeof(string));
            dte.Columns.Add("XueTangCeShiCiShu", typeof(string));
            dte.Columns.Add("ChaKan", typeof(string));
            dte.Columns.Add("PatientId", typeof(string));
            dte.Columns.Add("VISIT_ID", typeof(string));
            for (int i = 0; i < PatientNameList.Count; i++)
            {
                dte.Rows.Add(PatientNameList[i], PatientDiXueTangCiShuList[i], PatientXueTangCiShuList[i], "双击查看", HUanZheIDList[i], ZhuYuanCiShuList[i]);
            }
            gridControl1.DataSource = dte;
        }
        #endregion

        #region 双击事件
        private void bandedGridView1_DoubleClick(object sender, EventArgs e)
        {
            string DiXueTangFaShengCiShu = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "DiXueTangFaShengCiShu").ToString();      //低血糖发生次数
            string HuanZheXingMing = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "HuanZheXingMing").ToString();        //患者姓名
            string HuanZheId = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "PatientId").ToString();      //患者Id
            string ZhuYuanCiShu = bandedGridView1.GetRowCellValue(bandedGridView1.FocusedRowHandle, "VISIT_ID").ToString();        //住院次数
            LookOverHypoglycemia lohy = new LookOverHypoglycemia(LoginUser, PatientInfo, DiXueTangFaShengCiShu, DiXueTangFaShengShiJian, HuanZheXingMing, HuanZheId, ZhuYuanCiShu);
            lohy.ShowDialog();
        }
        #endregion
    }
}